package cn.johnyu.product.controller;

import cn.johnyu.commons.dto.ProductDto;
import cn.johnyu.product.mapper.ProductMapper;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.lang.management.ManagementFactory;
import java.util.concurrent.TimeUnit;

@RestController
public class ProductController {

    @Autowired
    private ProductMapper productMapper;

    @GetMapping("/info")
    @SentinelResource(value = "info",blockHandler = "infoFallback")
    public String info(@RequestHeader(value = "token",required = false) String token){
//        try {
//            TimeUnit.MILLISECONDS.sleep(1500);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        String processInfo = ManagementFactory.getRuntimeMXBean().getName();
        String threadInfo = Thread.currentThread().getName();

        return processInfo+ " :: "+threadInfo+"....."+token;

    }
    public String infoFallback(String token, BlockException e){
        return "限流处理";
    }


    @GetMapping("/products/{id}")
    @SentinelResource(value = "loadProductById",blockHandler = "loadFallback")
    public ProductDto loadProduct(@PathVariable int id){
        return productMapper.loadProduct(id);
    }

    public ProductDto loadFallback(int id,BlockException e){
        return new ProductDto().setId(-1).setName("waringin").setStock(-1);
    }

    @Transactional
    @PutMapping("/reduceStock")
    public int reduceStock(int id,int count){
        int stock = productMapper.loadProduct(id).getStock();
        if(count>stock) throw new RuntimeException("库存不足");
        return productMapper.reduceStock(id, count);
    }
}
